package com.delayqueue.core.queue;

import com.delayqueue.common.task.Task;
import com.delayqueue.core.common.RandomUtil;
import com.delayqueue.core.common.StringUtil;
import com.delayqueue.core.common.TimeUtil;
import com.delayqueue.core.permanent.PermanentHandler;
import com.delayqueue.core.thread.ThreadHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class QueueHandler {

    @Autowired
    private ThreadHandler threadHandler;

    @Autowired
    private QueueConsumer queueConsumer;

    @Autowired
    private PermanentHandler permanentHandler;

    public void addNewTask(Task task) {
        addNewTask(task, true);
    }

    public void addNewTask(Task task, boolean isPermanent) {

        if (StringUtil.isEmpty(task.getCode())) {
            String code = TimeUtil.format("yyyyMMddHHmmss") + RandomUtil.getRandomNum(20);
            task.setCode(code);
        }
        if (isPermanent) {
            permanentHandler.addTask(task);
        }
        QueueData.addTask(task);
    }

    public void start() {
        threadHandler.execute(queueConsumer);
        log.info("已经开始执行队列");
    }

    public void deleteTask(Task task) {
        permanentHandler.addCompleted(task);
        QueueData.delete(task);
    }
}
